package com.ssm.demo.util;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import jakarta.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author 银喾
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class PageBean {

    private int total;
    private int page = 1;
    private int rows = 5;
    private boolean pagination = true;
    private String url;
    private Map<String, String[]> ms;

    public void setMs(Map<String, String[]> ms) {
        this.ms = ms;
    }

    public int calcStartIndex() {
        return (page - 1) * rows;
    }

    public int calcMaxPage() {
        return total % rows == 0 ? total / rows : total / rows + 1;
    }

    public int nextPage() {
        return Math.min(page + 1, calcMaxPage());
    }

    public int prevPage() {
        return Math.max(page - 1, 1);
    }

    public void setRequest(HttpServletRequest req) {
        setUrl(req.getRequestURL().toString());
        setMs(req.getParameterMap());
        String page = req.getParameter("page");
        if (page == null) {
            setPage(1);
        } else {
            setPage(Integer.parseInt(page));
        }
        String rows = req.getParameter("rows");
        if (rows == null) {
            setRows(5);
        } else {
            setRows(Integer.parseInt(rows));
        }
        String pagination = req.getParameter("pagination");
        if ("false".equals(pagination)) {
            setPagination(false);
        }
    }

}